/*
 * 元素库中表意元素
 * @Author: evan.wan
 * @Date:   2016-06-25 15:55:20
 */

'use strict';
define([
    '../../../common/service',
    '../../../common/kit',
    './addElementDialog',
    'text!../tpl/allSimpleElement.html',
    'text!../tpl/allElementGroup.html'
], function(
    http,
    Kit,
    AddElementDialog,
    tpl,
    elementGroupTpl
) {
    function AllSimpleElement() {
        var self = this;
        var options={
            animation:true,
            trigger:'hover' //触发tooltip的事件
        }
        this.init = function(callback) {
            self.callback = callback;
            self.$root = $('#tab-content0');
            self.render();
        }

        this.render = function() {
            self.$root.html(I18N.parse(tpl, 'elementList'));
            self.$elementContainer = self.$root.find('.element-result-container');
            self.initSelect();
            self.event();
        }

        this.event = function() {
            self.getElementSmallCategory();
            //modal打开先请求元素数据
            self.$root.find('#search-area .btn-primary').off('click').on('click', $.proxy(self.openAddElementDialogb, self));
            $('#uploadSimpleEleb').change(function() {
                self.uploadSimpleEleb();
            })

        }
        this.initPage = function(total){
            $("div.ndp-page-wrapper[name=allSimpleElementPage]").page({
                totalPages:total
            }).off("PAGE_CHANGE").on("PAGE_CHANGE",function(e){//页数点击 事件
                console.log(e.originalEvent.data);//{currentPage: 第几页 int}
                self.filterFindElements(e.originalEvent.data.currentPage);
            });
            console.log(total);
            if(total == 1){
                //总共只有一页
                $('.page-item[role=end]').addClass("disabled");
            }
        }
        this.initSelect = function() {
            $("div.ndp-drop-wrapper[name=inline-drop1]").drop({
                data:[{
                    value: '0',
                    text: I18N.getText('templateDetail', 'allElementLevel')
                }, {
                    value: 'F',
                    text: I18N.getText('templateDetail', 'mainStyle')
                }, {
                    value: 'S',
                    text: I18N.getText('templateDetail', 'helpStyle')
                }],
                name:"elementLevel"
            }).on("ITEM_CLICK",function(e){
                self.filterFindElements();
            }).val({
                value: '0',
                text: I18N.getText('templateDetail', 'allElementLevel')
            });

            var elementTypeArr = [{value : '0', text : I18N.getText('templateDetail', 'allElementType')}];
            http.work('/ectemplatedetail/getElementBigCategory', null,'POST').then(function(res){
                if (res.succeed){
                    $.each(res.data, function(i,v){
                        elementTypeArr.push({value: v.id, text: v.name});
                    });
                    $("div.ndp-drop-wrapper[name=inline-drop2]").empty().drop({
                        data : elementTypeArr,
                        name : "elementType"
                    }).on("ITEM_CLICK",function(e){
                        self.getElementSmallCategory();
                    }).val({
                        value : '0',
                        text : I18N.getText('templateDetail', 'allElementType')
                    });

                } else {
                    Kit.alert2(res.errorMsg);
                }
            });
        }

        /**
         * 获取元素二级分类
         */
        this.getElementSmallCategory = function() {
            var param = {
                elementType: self.$root.find('input[name="elementType"]').attr('data-val') || 0
            }
            http.work('/ectemplatedetail/getElementSmallCategory', param, 'POST').then(function(res) {
                if (res.succeed) {
                    self.smallCategory = res.data;
                    self.filterFindElements();
                } else {
                    Kit.alert2(res.errorMsg);
                }
            });
        }

        /**
         * 添加元素dialog
         */
        this.openAddElementDialogb = function() {
            $('#uploadSimpleEleb').trigger('click');
        }
        /**
         * 通过颜色过滤元素
         */
        this.filterByColor = function(e) {
            var _tE = e.target;
            $(_tE).parents(".element-color-select").find(".circle").removeClass("active");
            $(_tE).addClass("active");
            var color = $(e.currentTarget).data('color');
            var param = {
                templateId: self.templateId,
                elementLevel: $(e.currentTarget).parent().parent().data('style'),
                elementType: self.$root.find('input[name="elementType"]').data('val') || 0,
                color: color || 'black',
                cPage:0,
                pSize:10
            }
            var imgContainerArea = $(e.currentTarget).parent().parent().parent().parent().next().find('ul');
            Kit.loading.show(imgContainerArea);
            http.work('/ectemplate/filterForPage', param,'POST').then(function(res){
                if (res.succeed){
                    imgContainerArea.empty();
                    $("div[name=allSimpleElementPage]").empty();
                    if(res.data.paginator.tSize == 0){
                        return false;
                    }
                    var eles = [];
                    _.each(res.data.data, function(option) {
                        eles.push(option.parentCode);
                        var liClass = "";
                        if (!option.elementPreview && option.elementImg){
                            liClass = "default-i";
                        }
                        imgContainerArea.append('<li class="' + liClass + '"><div class="element-img-div" data-toggle="tooltip" title="'+ option.elementName +'"><img class="liImg" data-id="' + option.id + '" src="' + (option.elementPreview ? option.elementPreview : option.elementImg) + '" /></div></li>');
                    });
                    _.each(self.smallCategory, function(m) {
                        if ($.inArray(m.code, eles) == -1) {
                            var tempStr = "";
                            if(m.context.length >15){
                                tempStr = m.context.substr(0,15);
                                tempStr+= "...";
                            }else{
                                tempStr = m.context;
                            }
                            imgContainerArea.append('<li><div class="element-font-div">'+ tempStr +'</div></li>');
                        }
                    });
                    self.adjuestElementGroup();
                    $(window).resize(function() {
                        self.adjuestElementGroup();
                    });
                    self.initPage(res.data.paginator.tPage);
                } else {
                    Kit.alert2(res.errorMsg);
                }
                $("[data-toggle='tooltip']").tooltip(options);
                Kit.loading.hide(imgContainerArea);
            });
        }

        /**
         * 展开此种类元素
         */
        this.findThisTypeAllElement = function(e) {
            var $swap = $(e.currentTarget);
            var fold = I18N.getText('templateDetail', 'expandAll') + '&nbsp;&nbsp;<i class="glyphicon glyphicon-menu-down"></i>';
            var unfold = I18N.getText('templateDetail', 'shrinkAll') + '&nbsp;&nbsp;<i class="glyphicon glyphicon-menu-up"></i>';
            var t = $swap.hasClass('unfold') ? fold : unfold;
            var $lis = $swap.prev().find('ul li.unActive');
            $swap.html(t);
            $swap.hasClass('unfold') ? $lis.slideUp() : $lis.slideDown();
            $swap.toggleClass('unfold');
        }

        /**
         * 在模板上预览元素
         */
        this.openPreviewElementStyleDialog = function(id,_obj) {
            var _html = '',ids = [];
            http.work('/ectemplate/findAllNewEcTemplate', {},'POST').then(function(res){
                if(res.succeed){
                    //再查询一遍，查询出选中的模板
                    http.do('/ectemplate/findTemplateByGroupId', {groupId:id},'POST').then(function(result){
                        if(result.succeed){
                            $.each(result.data,function(j,d){
                                ids.push(d.id);
                            });
                            //显示table
                            $.each(res.data,function(i,obj){
                                if(obj.templateImg != undefined ){
                                    _html += '<tr><td><div name="checkboxWrapper"><input type="checkbox"  id="cus'+ obj.id
                                        +'" data-id="'+ obj.id +'" class="form-input"><label for="cus'+ obj.id +'"><span                                    ' +
                                        ' class="checkbox-mark"></span></label></div></td>';
                                    _html += '<td><img src="'+ obj.templateImg +'"/></td>'
                                    _html += '<td><div name="img">'+ obj.templateName + '</div></td></tr>'
                                }
                            });
                            $("table[name=templates] tbody").html(_html);
                            //遍历checkbox 勾中当前样式使用的模板
                            var count = 0;
                            $("div[name=checkboxWrapper] input[type=checkbox]").each(function(n){
                                if($.inArray(Number($(this).attr("data-id")),ids) != -1){
                                    count++;
                                    $(this).attr("checked","checked");
                                }
                            });
                            //显示勾选的数量
                            $("div[name=foot-wapper] span").html(count);
                            var model = self.$root.find('#preview-element-style').modal('show');
                            //bind model 上的event
                            self.bindModelEvent(model,id,_obj);
                        }
                    });

                }
            });
        }

        this.bindModelEvent = function(modelObj,groupId,$spanObj){
            //bind check checkbox
            self.$root.find(".modal-dialog input[type=checkbox]").unbind("click").bind('click',function(){
                var s = self.$root.find(".modal-dialog input[type=checkbox]:checked").length;
                $("div[name=foot-wapper] span").html(s);
            });

            //bind cancel
            self.$root.find(".modal-dialog button[name=cancel]").unbind("click").bind('click',function(){
                modelObj.modal('toggle')
            });
            //bind ok
            self.$root.find(".modal-dialog button[name=ok]").unbind("click").bind('click',function(){
                var templateIds = [];
                $("div[name=checkboxWrapper] input[type=checkbox]:checked").each(function(){
                    //update  the template 关联
                    templateIds.push($(this).attr('data-id'));
                });
                http.do('/ectemplate/bindTemplatesByStyleGroupId',
                    {groupId:Number(groupId),templateIds:templateIds.join()},'POST').then(function(res){
                    if(res.succeed){
                        Kit.alert_success(I18N.getText('templateDetail', 'linkedSuccess'));
                        //成功之后 hide 关联模板，清除数据，下次点击+号时重新请求。
                        if($spanObj.hasClass("glyphicon-minus")){
                            $spanObj.removeClass("glyphicon-minus")
                            $spanObj.toggleClass("glyphicon-plus");
                            $spanObj.parent().next('div').hide();
                            $spanObj.parent().next('div').empty();
                        }
                        //更改 数量
                        var num = $spanObj.parent().find('span[name=num]').html();
                        $spanObj.parent().find('span[name=num]').html(Number(num) + Number(res.data));
                    }else{
                        Kit.alert2(I18N.getText('templateDetail', 'linkedFail'));
                    }
                    modelObj.modal('toggle');
                });
            });
        }
        /**
         * 过滤刷新所有页面元素
         */
        this.filterFindElements = function(cPage) {
            var param = {
                templateId : self.templateId,
                elementLevel : self.$root.find('input[name="elementLevel"]').attr('data-val'),
                elementType : self.$root.find('input[name="elementType"]').attr('data-val') || 0,
                color: 'black',
                cPage:0,
                pSize:10
            }
            if(cPage != undefined){
                param.cPage = cPage - 1;
            }
            var loadingArea = self.$root.find('.element-result-container');
            Kit.loading.show(loadingArea);
            http.work('/ectemplate/filterForPage', param,'POST').then(function(res){
                if (res.succeed){
                    //init page
                    self.$elementContainer.empty();
                    $("div[name=allSimpleElementPage]").empty();
                    if(res.data.paginator.tSize == 0){
                        return false;
                    }
                    //一、解析成一组一组的元素，更易于渲染页面
                    var result = _.groupBy(res.data.data, function(n){return n.styleGroup});
                    $.each(result,function(i,obj){

                        var elementGroupEach = '<div class="element-group-each">';
                        //二、一组里面的 主要样式和 辅助样式分开
                        var elementGroup = _.groupBy(obj, function(o){return o.name});
                        var elementGroupArr = [];
                        var styleGroup = 0;
                        for(var q in elementGroup) {
                            styleGroup = elementGroup[q][0].styleGroup;
                            var smallCategoryTemp = [];      //临时存放此组样式中没有的二级分类
                            var hasTemp = [];                //此组样式包含的二级分类
                            var elementGroupList = elementGroup[q];
                            _.each(elementGroupList, function(l) {
                                hasTemp.push(l.parentCode);
                            });

                            _.each(self.smallCategory, function(m) {
                                if ($.inArray(m.code, hasTemp) == -1) {
                                    smallCategoryTemp.push(m.context);
                                }
                            });

                            elementGroupArr.push({
                                style: q,
                                category : smallCategoryTemp,
                                list:elementGroupList
                            });
                        }
                        _.each(elementGroupArr, function(el) {
                            elementGroupEach += self.initElementGroupHtml(el);
                        });
                        elementGroupEach += '<div class="element-group-preview-font"><span class="glyphicon glyphicon-plus"></span>&nbsp;'+ I18N.getText("templateDetail", "linked") +'<span name="num">0</span>'+I18N.getText("templateDetail", "template")+',<button type="button" class="btn btn-link">'+ I18N.getText("templateDetail", "manager") +'</button>	</div>';
                        //添加row
                        elementGroupEach +='<div class="row" que="'+ styleGroup +'"></div></div>';
                        self.$elementContainer.append(elementGroupEach);
                        self.$root.find('.element-img-unfold').off('click').on('click', $.proxy(self.findThisTypeAllElement, self));
                        self.$root.find('.circle').off('click').on('click', $.proxy(self.filterByColor, self));
                        self.$root.find('.circle-black').addClass('active');
                        //bind + 号展开事件，显示关联模板数量
                        var $span = $('.element-group-preview-font>span.glyphicon').last();
                        self.initTemplateGroup($span,styleGroup);
                        $span.unbind('click').bind('click', function(){
                            self.showTemplate(this,styleGroup);
                        });
                        $('.element-group-preview-font button').last().unbind('click').bind('click', function(){
                            self.openPreviewElementStyleDialog(styleGroup,$span);
                        });
                    });
                    self.adjuestElementGroup();
                    self.hidenUnActive();
                    $(window).resize(function() {
                        self.adjuestElementGroup();
                    });
                    self.initPage(res.data.paginator.tPage);
                } else {
                    Kit.alert2(res.errorMsg);
                }
                $("[data-toggle='tooltip']").tooltip(options);
               Kit.loading.hide(loadingArea);
            });
        }
        this.initTemplateGroup = function($span,groupId){
            //查询模板，如果已经有的话就不去查询了
            var $row = $span.parent().next('div');
            if($row.html() == ""){
                var _html = "";
                http.do('/ectemplate/findTemplateByGroupId', {groupId:groupId},'POST').then(function(res){
                    if(res.succeed){
                        $.each(res.data,function(i,obj){
                            _html += ' <div class="col-xs-1 col-md-1"><span class="thumbnail"><img src="'
                                + obj.templateImg + '" ></span></div>'
                        });
                        $('div[que='+groupId+']').html(_html);
                        $span.parent().find('span[name=num]').html(res.data.length);
                    }
                });
            }
        }
        this.showTemplate = function(obj,groupId){
            self.initTemplateGroup($(obj),groupId);
            if($(obj).hasClass("glyphicon-plus")){
                $(obj).removeClass("glyphicon-plus");
                $(obj).toggleClass("glyphicon-minus");
                $(obj).parent().next('div').show();
            }else{
                $(obj).removeClass("glyphicon-minus")
                $(obj).toggleClass("glyphicon-plus");
                $(obj).parent().next('div').hide();
            }
        }

        /**
         * 渲染每组元素
         */
        this.initElementGroupHtml = function(el) {
            var tmpHtml = _.template(I18N.parse(elementGroupTpl, 'templateDetail'))({
                d: el
            });
            return tmpHtml;
        }
        /**
         * 调整元素中图片的显示数量
         */
        this.adjuestElementGroup = function(e) {
            self.$root.find('.element-group-each-child').each(function() {
                var $container = $(this).find('.element-img-container');
                var $unfold = $(this).find('.element-img-unfold');
                var unfoldFlag = $unfold.hasClass('unfold');
                var w = $(this).width(); //包含图片的容器宽度
                var n = Math.floor(w / 94) * 2; //显示两行的数量
                $container.find('ul li').each(function(i, v) {
                    $(this).toggleClass('unActive', i >= n);
                    if (!unfoldFlag) {
                        $(this).hasClass('unActive') ? $(this).hide() : $(this).show();
                    }
                });
            });


            self.$root.find('.element-img-container').each(function() {
                var width = $(this).width() - 1; //外面容器的宽度.
                var n = Math.floor(width / 94); //显示1行的数量
                var w = 84 * n; //每个元素84px
                var marginRight = (width - w) / (n - 1); //margin-right的值,最后一个为0;
                $(this).find('ul li').css('margin-right', marginRight + 'px');
                $(this).find('ul li:nth-child(' + n + 'n)').css('margin-right', '0px');
            })


        }

        this.hidenUnActive = function() {
            self.$root.find('li.unActive').hide();
        }

        /**
         * 直接弹出上传表意元素框
         */
        this.uploadSimpleEleb = function() {
            var formData = new FormData($('#uploadSimpleEleFormb')[0]);
            $.ajax({
                url: apiUrl + "/ecelement/upload",
                data: formData,
                xhrFields: {
                    withCredentials: true
                },
                type: 'POST',
                cache: false,
                contentType: false,
                processData: false,
                success: function(result) {
                    Kit.alert_success(I18N.getText('elementList', 'uploadSuccess'));
                    self.filterFindElements();
                },
                error: function(result) {
                    console.info(result);
                }

            });
        }


    }
    return new AllSimpleElement();
});
